#include <jni.h>
#include <string>

using namespace std;

// 脚本解密
extern "C"
JNIEXPORT jbyteArray JNICALL
Java_com_fengxu_gamescript_util_CommonUtils_k(JNIEnv *env, jobject thiz, jbyteArray jbArr) {
    jstring key = env->NewStringUTF("D89475D32EA3AXE933DBD299599EEA3E");
    jstring charset = env->NewStringUTF("UTF-8");
    jclass strClass = env->GetObjectClass(key);
    jmethodID getBytesId = env->GetMethodID(strClass,"getBytes","(Ljava/lang/String;)[B");
    // 反射调用获取秘钥的byte数组
    jbyteArray keyByteArr = (jbyteArray)env->CallObjectMethod(key,getBytesId,charset);
    jsize keySize =  env->GetArrayLength(keyByteArr);
    jbyte* keyBytes = env->GetByteArrayElements(keyByteArr, JNI_FALSE);
    jsize sourceLen = env->GetArrayLength(jbArr);
    jbyte* sourceBytes = env->GetByteArrayElements(jbArr, JNI_FALSE);
    int i;
    // 进行异或加密
    for(i=0; i<sourceLen; i++){
        *(sourceBytes + i) = *(sourceBytes + i) ^ *(keyBytes + (i % keySize));
    }
    env->ReleaseByteArrayElements(keyByteArr, keyBytes, 0);
    env->ReleaseByteArrayElements(jbArr, sourceBytes, 0);
    return jbArr;
}


// 登录密码加密
extern "C"
JNIEXPORT jstring JNICALL
Java_com_fengxu_gamescript_util_CommonUtils_pEnc(JNIEnv *env, jobject thiz, jstring pwd) {
    // 创建StringBuilder
    jclass sbClass =  env->FindClass("java/lang/StringBuilder");
    // 获取构造
    jmethodID initMethod =  env->GetMethodID(sbClass,"<init>","(Ljava/lang/String;)V");
    // 获取append
    jmethodID appendMethod = env->GetMethodID(sbClass,"append", "(Ljava/lang/String;)Ljava/lang/StringBuilder;");
    // 获取toString
    jmethodID toStringMethod = env->GetMethodID(sbClass,"toString", "()Ljava/lang/String;");
    // 初始化StringBuilder
    jobject sb = env->NewObject(sbClass,initMethod,pwd);
    // 添加盐
    env->CallObjectMethod(sb,appendMethod, env->NewStringUTF("SDSVUHA!%^SB"));
    // 获取拼接后的字符串,对该字符串进行md5加密
    jstring lastPwd = (jstring)env->CallObjectMethod(sb,toStringMethod);
    // 获取md5方法ID
    jclass utilsClazz =  env->GetObjectClass(thiz);
    jmethodID md5MethodId =  env->GetMethodID(utilsClazz,"getMd5", "(Ljava/lang/String;)Ljava/lang/String;");
    // 获取进行了md5加密后的字符串
    lastPwd = (jstring)env->CallObjectMethod(thiz,md5MethodId,lastPwd);
    // 最后获取字符串截取的方法，截取2-18位
    jclass stringClass = env->FindClass("java/lang/String");
    jmethodID subStrMethodId = env->GetMethodID(stringClass,"substring", "(II)Ljava/lang/String;");
    return (jstring)env->CallObjectMethod(lastPwd,subStrMethodId,2,18);
}


// 获取网站请求的ipHost
extern "C"
JNIEXPORT jstring JNICALL
Java_com_fengxu_gamescript_util_CommonUtils_getHost(JNIEnv *env, jobject thiz) {
    return env->NewStringUTF("http://47.96.229.28");
}